public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    private Node[] array;
    private int size; // 当前数据个数
    private static final double LOAD_FACTOR = 0.75;

    public HashBucket() {
        this.array = new Node[8];
        this.size = 0;
    }

    /**
     * 插入值
     *
     * @param key
     * @param value
     * @return
     */
    public int put(int key, int value) {
        // 计算 index
        int index = key % array.length;
        // 遍历链表找是否存在key
        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (key == cur.key) {
                int oldValue = cur.value;
                cur.value = value;
                return oldValue;
            }
        }
        // 不存在插入新节点
        Node node = new Node(key, value);
        node.next = array[index];
        array[index] = node;
        size++;
        // 判断负载因子，大于 LOAD_FACTOR 扩容
        if (loadFactory() >= LOAD_FACTOR) {
            // 扩容
            resize();
        }
        return -1;
    }

    /**
     * 获取值
     *
     * @param key
     * @return
     */
    public int get(int key) {
        int index = key % array.length;
        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (cur.key == key) {
                return cur.value;
            }
        }
        return -1;
    }

    /**
     * 扩容
     *
     */
    private void resize() {
        // 创建大小为原数组大小两倍的新数组
        Node[] newArray = new Node[array.length * 2];
        // 移动复制数据
        for (Node node : array) {
            Node next;
            for (Node cur = node; cur != null; cur = next) {
                next = cur.next;
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
            }
        }
        // 将原数组替换为新数组
        array = newArray;
    }

    /**
     * 获取当前负载因子
     *
     * @return
     */
    private double loadFactory() {
        return size * 1.0 / array.length;
    }
}
